/**
 * Project   : android-utility
 * Package   : org.basagee.activities
 * File name : TwitterApp.java
 * Author    : Basagee
 * Date      : 2011. 4. 15.

 * Copyright
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.basagee.activities;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
import twitter4j.media.MediaProvider;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;

/**
 * @author Basagee
 *
 */
public class TwitterApp extends Activity implements View.OnClickListener {	 
	private Twitter mTwitter;
	private AccessToken mAccessToken;
	private RequestToken mRqToken;
	private Button mBtnLogin, mBtnFeed, mBtnLogout;
	private EditText mEditContent;
	SharedPreferences prefs;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.twitter_main);
	        
	        mEditContent = (EditText)findViewById(R.id.etContent);
	        mBtnLogin = (Button)findViewById(R.id.btnLogin);
	        mBtnFeed = (Button)findViewById(R.id.btnFeed);
	        mBtnLogout = (Button)findViewById(R.id.btnLogout);

	        // check token 
	        prefs = getSharedPreferences("TwitterPreference", MODE_PRIVATE);
	        String rqTokenString = prefs.getString("rqToken", null);
	        String tokenSecretString = prefs.getString("tokenSecret", null);
	        
	        if (rqTokenString == null || tokenSecretString == null) {
	        	mBtnLogin.setOnClickListener(this);
	        } else {
	        	Log.v(TwitterConst.TAG, "Load from persist storage !!!!");
	        	//mBtnLogin.setVisibility(View.INVISIBLE);
	        	mBtnLogin.setEnabled(false);
	        	mBtnLogin.setOnClickListener(null);
	        	
	        	ConfigurationBuilder cb = new ConfigurationBuilder();
	        	TwitterFactory tf = new TwitterFactory(cb.build());
	        	mTwitter = tf.getInstance();
	        	mTwitter.setOAuthConsumer(TwitterConst.TWITTER_CONSUMER_KEY, TwitterConst.TWITTER_CONSUMER_SECRET);
	         
	        	try {
	        		mAccessToken = new AccessToken(rqTokenString, tokenSecretString);
	        	} catch(Exception e) {
		    	}
	        	mTwitter.setOAuthAccessToken(mAccessToken);
	        }
	        
	        mBtnFeed.setOnClickListener(this);
	        mBtnLogout.setOnClickListener(this);
	}
	
	// click button
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin :		// Twitter login
			login();
			break;
		case R.id.btnFeed :			// write feed to twitter
			write();
			break;
		case R.id.btnLogout :
			logout();
			break;
		default :
			break;
		}
	}

	// Private twitter functions
	private void login() {
		try {
			ConfigurationBuilder cb = new ConfigurationBuilder();
			cb.setDebugEnabled(true);
			cb.setOAuthConsumerKey(TwitterConst.TWITTER_CONSUMER_KEY);
			cb.setOAuthConsumerSecret(TwitterConst.TWITTER_CONSUMER_SECRET);
			TwitterFactory factory = new TwitterFactory(cb.build());
			mTwitter = factory.getInstance();
			mRqToken = mTwitter.getOAuthRequestToken(TwitterConst.TWITTER_CALLBACK_URL);
			Log.v(TwitterConst.TAG, "AuthorizationURL >>>>>>>>>>>>>>> " + mRqToken.getAuthorizationURL());
	      
			Intent intent = new Intent(this, TwitterLogin.class);
			intent.putExtra("auth_url", mRqToken.getAuthorizationURL());
			startActivityForResult(intent, TwitterConst.TWITTER_LOGIN_CODE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Configuration getConfiguration(String apiKey) {
		return new ConfigurationBuilder().setMediaProviderAPIKey(apiKey).build();
	}

	private void write() {
		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
		String fileName = "example.jpg";
		InputStream is = null;
	    
		try {
			if (new File(path + File.separator + fileName).exists())
				is = new FileInputStream(path + File.separator + fileName);
			else
				is = null;

			ConfigurationBuilder cb = new ConfigurationBuilder();
			String oAuthAccessToken = mAccessToken.getToken();
			String oAuthAccessTokenSecret = mAccessToken.getTokenSecret();
			String oAuthConsumerKey = TwitterConst.TWITTER_CONSUMER_KEY;
			String oAuthConsumerSecret = TwitterConst.TWITTER_CONSUMER_SECRET;
			cb.setOAuthAccessToken(oAuthAccessToken);
			cb.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
			cb.setOAuthConsumerKey(oAuthConsumerKey);
			cb.setOAuthConsumerSecret(oAuthConsumerSecret);
			Configuration config = cb.build();
			OAuthAuthorization auth = new OAuthAuthorization(config);
	      
			TwitterFactory tFactory = new TwitterFactory(config);
			Twitter twitter = tFactory.getInstance();
			ImageUploadFactory iFactory = new ImageUploadFactory(getConfiguration(TwitterConst.TWITPIC_API_KEY));
			ImageUpload upload = iFactory.getInstance(MediaProvider.TWITPIC, auth);
	      
			if (is != null) {
				String strResult = upload.upload("example.jpg", is, mEditContent.getText().toString());
				twitter.updateStatus(mEditContent.getText().toString() + " " + strResult);
			} else
				twitter.updateStatus(mEditContent.getText().toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) is.close();
			} catch (Exception e) {}
		}
	}
	  
	private void logout() {
		Intent intent = new Intent(this, TwitterLogin.class);
		intent.setAction(TwitterConst.TWITTER_ACTION_LOGIN);
		intent.putExtra("auth_url", TwitterConst.TWITTER_LOGOUT_URL);
		startActivityForResult(intent, TwitterConst.TWITTER_LOGOUT_CODE);
	}
	  
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	    
		Log.v(TwitterConst.TAG, "requestCode = " + requestCode + ", resultCode = " + resultCode);
		// Login 액티비티가 정상적으로 종료되었을 경우
		if (resultCode == RESULT_OK) {
			if (requestCode == TwitterConst.TWITTER_LOGIN_CODE) {
				try {
					mAccessToken = mTwitter.getOAuthAccessToken(mRqToken, data.getStringExtra("oauth_verifier"));
	          
					Log.v(TwitterConst.TAG, "Twitter Access Token : " + mAccessToken.getToken());
					Log.v(TwitterConst.TAG, "Twitter Access Token Secret : " + mAccessToken.getTokenSecret());

			        // store presist storage 
					SharedPreferences.Editor ed = prefs.edit();
			 		ed.putString("rqToken", mAccessToken.getToken());
					ed.putString("tokenSecret", mAccessToken.getTokenSecret());
					Log.d("XXXX", "token saved !!!!!!!!!");
					ed.commit();

		    		mBtnLogin.setEnabled(false);
		        	mBtnLogin.setOnClickListener(null);
				} catch (Exception e) {
		        	e.printStackTrace();
		        }
			} else if (requestCode == TwitterConst.TWITTER_LOGOUT_CODE) {
				Log.v(TwitterConst.TAG, ">>> Logout from twitter !!!!");
				SharedPreferences prefs = getSharedPreferences("TwitterPreference", MODE_PRIVATE);
	    		SharedPreferences.Editor ed = prefs.edit();
	    		ed.remove("rqToken");
	    		ed.remove("tokenSecret");
	    		ed.commit();
	    		
	    		//mBtnLogin.setVisibility(View.VISIBLE);
	    		mBtnLogin.setEnabled(true);
	        	mBtnLogin.setOnClickListener(this);
			}
		}
	}
}
